<?php
namespace App\Logic;

class NewsLogic
{
	public $m;

	public function __construct()
	{
		$this->m = M('news');
	}

	public function ls()
	{
		$where = array();

		//对分类搜索特殊处理，去掉id后面的
		cate_where();
		//自动构造搜索条件
		$where = parseWhere();

		//列表
		$page = isset($_POST['page']) ? $_POST['page'] : 1;
		$page = max($page, 1);
		$size = isset($_POST['size']) ? $_POST['size'] : 15;
		$start = $page * $size - $size;


		$prop = $_POST['prop'] ? $_POST['prop'] : 'id';
		if($prop == 'cate') $prop = 'cate_id';
		if($_POST['order'] == 'desc') {
			$order = 'DESC';
		}elseif($_POST['order'] == 'asc') {
			$order = 'ASC';
		}
		if($order) {
			$this->m->order("$prop $order");
		}
		$data = $this->m->where($where)->limit($start, $size)->select();

		foreach ($data as &$d) {
			$d['cate'] = getCate($d['cate_id']);
		}
		$total = $this->m->where($where)->count();

		return array('st' => 1, 'data' => $data, 'total' => $total);
	}

	public function get($id)
	{
		$id = (int) $id;
		$row = $this->m->find($id);
		$row['custom'] = json_decode($row['custom'], true);
		if(!$row['custom']) {
			$row['custom'] = new \stdClass();
		}
		return array('st' => 1, 'data' => $row);
	}

	public function save($post)
	{
		$id = (int) $post['id'];
		$post['custom'] = json_encode($post['custom'], 256);
		if($id) {
			$rs = $this->m->where("id = $id")->save($post);
			if($rs !== false) {
				return array('st' => 1);
			}
		}else{
			$post['admin_id'] = ADMIN_ID;
			$post['admin_name'] = getAdmin(ADMIN_ID);
			$rs = $this->m->add($post);
			if($rs !== false) {
				return array('st' => 1, 'id' => $rs);
			}
		}
		return array('st' => 0, 'msg' => '保存错误');
	}

	public function del($id)
	{
		$id = (int) $id;
		if(!$id) json(0, '参数错误');
		$rs = $this->m->where("id = $id")->delete();
		if($rs === false) {
			return array('st' => 0, 'msg' => '删除失败');
		}else{
			return array('st' => 1);
		}
	}
}